package com.kxj.gaode;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GaodePlugin extends CordovaPlugin {
	private String TAG = "GaodePlugin";
	private CallbackContext callbackContext;
	private LocationChangeReceiver locationChangeReceiver;

	@Override
	public boolean execute(String action, JSONArray jsonArray,
			CallbackContext callbackContext) throws JSONException {
		this.callbackContext = callbackContext;
		// 高德导航
		if ("GaodeNavigation".equals(action)) {
			Intent intent = new Intent(getContext(), GaodeNaviActivity.class);
			intent.putExtra("latLngList", jsonArray.toString());

			getContext().startActivity(intent);
			callbackContext.success("success");
			return true;
		}
		// 高德定位
		if ("GaodeLocation".equals(action)) {
			openGPS();
			
			// 启动定位服务
			Intent intent = new Intent(getContext(), LocationService.class);
			intent.addFlags(5566);
			getContext().stopService(intent);
			intent.putExtra("locationOptions", jsonArray.toString());
			getContext().startService(intent);
			
			// 注册一个广播接收者，用于接受位置改变时发送的广播

			if (locationChangeReceiver == null) {
				locationChangeReceiver = new LocationChangeReceiver();
				IntentFilter intentFilter = new IntentFilter(
						"com.kxj.locationChanged");
				getContext().registerReceiver(locationChangeReceiver,
						intentFilter);
			}
			return true;
		}
		// 高德地图
		if ("GaodeMap".equals(action)) {
			Intent intent = new Intent(getContext(), GaodeMapActivity.class);
			getContext().startActivity(intent);
			callbackContext.success("success");
			return true;
		}

		callbackContext.error("error");
		return false;
	}

	/**
	 * 获取上下文
	 */
	private Context getContext() {
		return cordova.getActivity();
	}

	/**
	 * @author kxj
	 * @description 接收位置改变时发送的广播
	 */
	class LocationChangeReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("com.kxj.locationChanged")) {

				Log.i(TAG, "接收到位置改变的广播");
				Bundle bundle = intent.getExtras();
				JSONObject jsonObj = new JSONObject();
				try {
					jsonObj.put("latitude", bundle.get("latitude"));
					jsonObj.put("longitude", bundle.get("longitude"));
					jsonObj.put("address", bundle.get("address"));
					jsonObj.put("city", bundle.get("city"));
					jsonObj.put("locationType", bundle.get("locationType"));
					jsonObj.put("errorInfo", bundle.get("errorInfo"));
					jsonObj.put("errorCode", bundle.get("errorCode"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
				PluginResult result = new PluginResult(Status.OK, jsonObj);
				result.setKeepCallback(true);
				callbackContext.sendPluginResult(result);
				if (bundle.getBoolean("isOnceLocation")) {
					// 单次定位,获取到定位结果后,关闭定位服务,注销广播
					getContext().stopService(
							new Intent(getContext(), LocationService.class));
					//getContext().unregisterReceiver(this);
				}
			}
		}
	}

	private String[] permissions = { Manifest.permission.ACCESS_FINE_LOCATION };
	private int requestCode = 456;

	private void openGPS() {

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			int checkGPS = ContextCompat.checkSelfPermission(
					cordova.getActivity(), permissions[0]);
			if (checkGPS != PackageManager.PERMISSION_GRANTED) {
				ActivityCompat.requestPermissions(cordova.getActivity(),
						permissions, requestCode);
			}

		}
	}
}
